import tools from '@/utils/tools'
import router from '@/router'
import { loginPwd, getLoginCode, loginCode, getUserInfo, userUpdate } from '@/api/user'

import { Message } from 'element-ui'

const oldState = {
  // token
  hfSession: tools.storage.getHfSession(),
  // userInfo
  userInfo: {},
  // 登录错误提示
  errorMessage: '',
  // 验证码登录图形验证码
  captcha: '',
  // 常规设置
  generalSettings: {
    // 打开麦克风
    voiced: true,
    // 打开摄像头
    camera: true,
    // 显示参会时长
    durationOfAttendance: true
  }
}

const state = JSON.parse(JSON.stringify(oldState))

const mutations = {
  // 还原初始状态
  set_state (state) {
    for (const key in state) {
      state[key] = oldState[key]
    }
  },
  // 设置token
  set_hfSession (state, token) {
    state.hfSession = token
  },
  // 设置userInfo
  set_userInfo (state, obj) {
    state.userInfo = obj
  },
  // 设置登录错误提示
  set_errorMessage (state, mes) {
    state.errorMessage = mes
  },
  // 设置验证码登录图形验证码
  set_captcha (state, captcha) {
    state.captcha = captcha
  },
  // 设置是否打开麦克风
  set_generalSettings_voiced (state, voiced) {
    state.generalSettings.voiced = voiced
  },
  // 设置是否打开摄像头
  set_generalSettings_camera (state, camera) {
    state.generalSettings.camera = camera
  },
  // 设置是否显示参会时长
  set_generalSettings_durationOfAttendance (state, durationOfAttendance) {
    state.generalSettings.durationOfAttendance = durationOfAttendance
  }
}

const actions = {
  // 获取用户信息
  getUserInfo ({ commit, dispatch, rootState }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(async res => {
        if (res.data && res.data.code === 200) {
          commit('chatInformation/add_user', {
            userID: res.data.data.user_id,
            userInfo: {
              user_name: res.data.data.user_name,
              user_phone: res.data.data.user_phone,
              user_img_id: res.data.data.user_img
            }
          }, { root: true })
          commit('set_userInfo', res.data.data)
          dispatch('addressList/getMyAddressList', {}, { root: true })
          if (!rootState.socket.webSocket) {
            dispatch('socket/initWS', {}, { root: true })
          }
        } else {
          Message({
            type: 'error',
            message: '登录过期，请重新登录！'
          })
          router.push('/Login')
        }
      })
    })
  },
  // 密码登录
  loginByPwd ({ commit, rootState }, { phone, password, captcha }) {
    return new Promise((resolve, reject) => {
      loginPwd(phone, password, captcha).then(res => {
        if (res.data.code === 200) {
          commit('set_hfSession', res.data.data.token)
          tools.storage.setHfSession(res.data.data.token)
          Message({
            type: 'success',
            message: res.data.message
          })
          router.push('/home')
        } else if (res.data.code === 502) {
          if (!rootState.common.showImgDialog) {
            commit('common/set_showImgDialog', true, { root: true })
            commit('common/set_fnName', 'user/loginByPwd', { root: true })
            commit('common/set_fnParams', { phone, password }, { root: true })
            commit('common/set_imgCode', '', { root: true })
          } else {

          }
        } else {
          commit('set_errorMessage', res.data.message)
        }
        resolve(res)
      })
    })
  },
  // 获取手机验证码
  getPhoneCode ({ commit }, params) {
    return new Promise((resolve, reject) => {
      let code
      if (params && params.captcha) {
        code = params.captcha
        commit('set_captcha', code)
      }
      getLoginCode(params.phone, code).then(res => {
        if (res.data.code === 200) {
          tools.countDown(60)
        } else {
          commit('set_errorMessage', res.data.message)
        }
        resolve(res)
      })
    })
  },
  // 手机验证码登录
  loginByCode ({ state, commit }, { phone, password }) {
    return new Promise((resolve, reject) => {
      loginCode(phone, password, state.captcha).then(res => {
        if (res.data.code === 200) {
          commit('set_hfSession', res.data.data.token)
          tools.storage.setHfSession(res.data.data.token)
          router.push('/home')
          Message({
            type: 'success',
            message: res.data.message
          })
        }
        resolve(res)
      })
    })
  },
  // 更新用户信息
  // eslint-disable-next-line camelcase
  updateUser ({ commit, dispatch }, { name, phone, password, confirm_password, img }) {
    return new Promise((resolve, reject) => {
      userUpdate({ name, phone, password, confirm_password, img }).then(res => {
        if (res.data && res.data.code === 200) {
          dispatch('file/downloadFile', { fileType: 1, fileID: res.data.data.user_img }, { root: true }).then(result => {
            res.data.data.user_img = tools.dataDealer.blobToUrl(result)
            commit('set_userInfo', res.data.data)
            commit('chatInformation/add_user', {
              userID: res.data.data.user_id,
              userInfo: {
                user_name: res.data.data.user_name,
                user_img: res.data.data.user_img
              }
            }, { root: true })
          })
        }
        resolve(res)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
